package pl.un4giv3n.mightvsmagic.action;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import pl.un4giv3n.mightvsmagic.entity.Action;
import pl.un4giv3n.mightvsmagic.entity.ActionType;
import pl.un4giv3n.mightvsmagic.entity.SpecialSkillTemplate;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.utils.ActionUtil;
import pl.un4giv3n.mightvsmagic.utils.UserUtil;

/**
 * @author andrzejewskia
 *	shows development page
 */
public class DevelopPageAction extends PersistenceAction {

	private static final long serialVersionUID = 1L;
	/**
	 * session user
	 */
	protected User user;
	/**
	 * current action performed by user
	 */
	private Action currentAction;
	private Set<SpecialSkillTemplate> avaibleSpecialSkills;

	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		currentAction = user.getCurrentAction();
		if (currentAction != null
				&& currentAction.getActionType().equals(ActionType.FIGHT)) {
			if (ActionUtil.actionEnded(currentAction, user)) {
				EntityTransaction transaction = entityManager
						.getTransaction();
				transaction.begin();
				user.setCurrentAction(Action.NO_ACTION);
				entityManager.merge(user);
				entityManager.flush();
				transaction.commit();
				currentAction = Action.NO_ACTION;
			}
		}
		avaibleSpecialSkills = new HashSet<SpecialSkillTemplate>(); 
		avaibleSpecialSkills.addAll(UserUtil.getNextAvaibleToLearnSpecialSkills(user, entityManager));
		entityManager.close();
		if (currentAction == null || currentAction.equals(Action.NO_ACTION)) {
			return SUCCESS;
		} else {
			addActionError(ActionUtil.generateErrorMessage(currentAction, user));
			return INPUT;
		}
	}

	public User getUser() {
		return user;
	}
	/**
	 * @return action end time formated as string for javascript countdown
	 */
	public String getActionEndString(){
		return ActionUtil.getActionEndDate(currentAction, user);
	}
	
	public Set<SpecialSkillTemplate> getAvaibleSpecialSkills(){
		return avaibleSpecialSkills;
	}
	
}
